<template>
  <div id="dom" style="width: 400px; height: 400px">图表5</div>
</template>

<script>
import * as echarts from "echarts";
import axios from "axios";
import { onMounted } from "vue";
export default {
  name: "one5",
  setup() {
    onMounted(() => {
      datainit();
    });
    let dataAll = [];
    let bool = false;
    const datainit = () => {
      let url = "/api/total";
      axios.get(url).then((res) => {
        console.log(res);
        let data = res.data;
        for (let i in data) {
          const districtsData = data[i].districts;
          const districtValue = districtsData.map((district) => ({
            name: district.name,
            Gtp: district.Gtp,
          }));
          const sum = districtValue.reduce(
            (accumulator, district) => accumulator + district.Gtp,
            0
          );
          const average = sum / districtValue.length;
          // console.log(average);
          //第一部分先求出各市区的平均值，并赋值给新的变量average
          for (let j in dataAll) {
            if (dataAll[j].name == data[i].region) {
              dataAll[j].value += average;
              bool = true;
            }
          }
          if (!bool) {
            let map = { name: data[i].region, value: average };
            dataAll.push(map);
          }
          bool = false;
        }
        //第二阶段是先将data的数据改到dataAll中方便后期取值，在将dataAll中的name重复的进行相加
        dataAll.sort((a, b) => b.value - a.value);

        dataAll = dataAll.slice(0, 10);
        //三 排序并取前十数据
        let citys = [];
        let buys = [];
        for (let i in dataAll) {
          citys.push(dataAll[i].name);
          buys.push(dataAll[i].value);
        }
        console.log(citys);
        console.log(buys);
        init(citys, buys);
        // 四，将dataAll中的name,value,赋值给新的变量并在控制台打印输出
      });
    };
    const init = (citys, buys) => {
      let option = {
        title: {
          text: "2023年雷达图图展示省份的平均消费额,包含平均值计算reduce",
        },
        xAxis: {
          name: "省份",
          data: citys,
        },
        yAxis: {
          name: "平均消费额",
        },
        series: [
          {
            type: "scatter",
            data: buys,
          },
        ],
      };
      let myChart = echarts.init(document.getElementById("dom"));
      myChart.setOption(option);
    };
  },
};
</script>

<style></style>